package com.fire.modules.wx;

import com.fire.modules.api.service.TbTokenService;
import com.fire.modules.api.service.TbUserService;
import com.fire.modules.entity.TbUser;
import com.fire.utils.UidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 授权后的回调请求处理
 */
@RestController
@RequestMapping("/oauth")
public class OAuthController {

    @Autowired
    private TbUserService tbUserService;

    @Autowired
    private TbTokenService tokenService;


    @GetMapping("/auth")
    public ModelAndView doGet(HttpServletRequest request, HttpServletResponse response,String userCode,String houseCode) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        // 用户同意授权后，能获取到code
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        System.out.println("++++++++++++++++++++++++++++++++++++++++userCode"+userCode);
        System.out.println("++++++++++++++++++++++++++++++++++++++++housesCode"+houseCode);
        System.out.println("++++++++++++++++++++++++++++++++++++++++"+code);
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+state);
        Map<String, Object> map = new HashMap<>();
        // 用户同意授权
        if (!"authdeny".equals(code)) {
            // 获取网页授权access_token
            WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getOauth2AccessToken("", "", code);
            // 网页授权接口访问凭证
            String accessToken = weixinOauth2Token.getAccessToken();
            // 用户标识
            String openId = weixinOauth2Token.getOpenId();
            // 获取用户信息
            SNSUserInfo snsUserInfo = AdvancedUtil.getSNSUserInfo(accessToken, openId);

            TbUser tbUser = tbUserService.queryOpenId(snsUserInfo.getOpenId());
            //使用openid判断是否注册
            if (tbUser == null) {
                //未注册，注册
                tbUser = new TbUser();
                tbUser.setUserCode(UidUtil.getUUID());
                tbUser.setWximpurl(snsUserInfo.getHeadImgUrl());
                tbUser.setWxname(snsUserInfo.getNickname());
                tbUser.setSex(snsUserInfo.getSex());
                tbUser.setUsername(snsUserInfo.getNickname());
                tbUser.setWxoppenid(snsUserInfo.getOpenId());
                tbUser.setDelete_type(0);
                tbUser.setCreate_Time(new Date());
                if(userCode != null && !userCode.equals("") && !userCode.equals("0")){
                    tbUser.setFirstCode(userCode);
                }
                tbUserService.save(tbUser);
                tokenService.createToken(tbUser.getUserId());
            } else {
                //已注册则更新资料
                tbUser.setWximpurl(snsUserInfo.getHeadImgUrl());
                tbUser.setWxname(snsUserInfo.getNickname());
                tbUser.setSex(snsUserInfo.getSex());
                tbUser.setUsername(snsUserInfo.getNickname());
                if(userCode != null && !userCode.equals("") && !userCode.equals("0")){
                    tbUser.setFirstCode(userCode);
                }
                tbUserService.update(tbUser);
            }
            map = tokenService.createToken(tbUser.getUserId());
            // 设置要传递的参数
            request.setAttribute("snsUserInfo", snsUserInfo);
            request.setAttribute("state", state);
        }
        // 跳转到index.jsp
//         request.getRequestDispatcher("www.guangtouboy.com").forward(request, response);
//        ModelAndView view = new ModelAndView("redirect:http://www.guangtouboy.com/#/Login?token=" + map.get("token").toString());
//        view.addObject("state",state);
//        return view;
        return new ModelAndView("redirect:http://kkf.youwenyuedu.com/#/Login?state=" + state + "&token=" + map.get("token").toString()+"&houseCode="+houseCode);
//        return new ModelAndView("redirect:http://kkf.youwenyuedu.com/#/Login?state=1&token=1");

}
}
